package com.isyscore.os.driver.protocol;


import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Data
public class ProtocolRequestData {
    private static final Logger logger = LoggerFactory.getLogger(ProtocolRequestData.class);
    /**
     * 包头
     */
    public static final byte header = 0x68;
    /**
     * 电表地址号 6个字节
     */
    private byte[] addressNum = new byte[6];
    /**
     * 控制码
     */
    public  byte controlCode;
    /**
     * 数据域长度
     */
    private byte dataLength;
    /**
     * 数据域
     */
    private byte[] dataIdentifier = new byte[2];
    /**
     * 校验码1个字节
     */
    private byte checkCode;
    /**
     * 包尾
     */
    public static final byte tail = 0x16;



    public ProtocolRequestData(byte[] addressNum,byte controlCode,byte dataLength,byte[] dataIdentifier) {
        this.addressNum = addressNum;
        this.controlCode = controlCode;
        this.dataLength = dataLength;
        this.dataIdentifier = dataIdentifier;
        computeCheckCode();
    }
    private void computeCheckCode() {
        byte[] buffer = new byte[12];
        buffer[0] = ProtocolRequestData.header;
        System.arraycopy(this.addressNum, 0, buffer, 1, this.addressNum.length);
        buffer[7] = ProtocolRequestData.header;
        buffer[8] = this.controlCode;
        buffer[9] = this.dataLength;
        for (int i = 0; i < this.dataLength; i++) {
            this.dataIdentifier[i] = (byte) (this.dataIdentifier[i] + 0x33);
        }
        System.arraycopy(this.dataIdentifier, 0, buffer, 10, this.dataIdentifier.length);

        int sum = 0;
        for (byte b:buffer) {
            sum += b;
        }

        this.checkCode = (byte)(sum%256);

    }

    public byte[] encode() {
        ByteArrayOutputStream out = new ByteArrayOutputStream(14);
        try {
            out.write(ProtocolRequestData.header);
            out.write(this.addressNum);
            out.write(ProtocolRequestData.header);
            out.write(this.controlCode);
            out.write(this.dataLength);
            out.write(this.dataIdentifier);
            out.write(this.checkCode);
            out.write(ProtocolRequestData.tail);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

}